package com.atguigu4;

import com.utils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Scanner;

/**
 *  课后练习1，从控制台输入数据，插入到表Customers中
 * @auther user
 * @date 2021/12/7 - 2:44
 */
public class Exer1Test {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String name = scanner.nextLine();
        System.out.println("请输入邮箱：");
        String email = scanner.nextLine();
        System.out.println("请输入生日：yyyy-MM-dd");
        String date = scanner.nextLine();
        //类型转换 String-java.util.Date-java.sql.Date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date parse = simpleDateFormat.parse(date);
        Date birth = new Date(parse.getTime());

        String sql = "insert into customers(name,email,birth) values(?,?,?)";
        Exer1Test exer1Test = new Exer1Test();
        int i = exer1Test.customersUpdate(sql, name, email, birth);
        if (i > 0){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
    }
    //executeUpdate() 如果执行查询操作，返回的是什么
    //java.sql.SQLException: Can not issue executeUpdate() for SELECTs
    @Test
    public void testexecuteUpdate(){
        String sql = "select id,name,email,birth from customers";
        Exer1Test exer1Test = new Exer1Test();
        int i = exer1Test.customersUpdate(sql);
        System.out.println("i = " + i);
    }

    /**
     * 针对于cusyomers表的更新操作
     * @param sql
     * @param args
     * @return
     */
    public int customersUpdate(String sql,Object ...args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int i = 0;
        try {
            //1 获取连接
            connection = JDBCUtils.getConnection();
            //2 预编译sql,返回preparedStatment实例
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            for (int j = 0; j < args.length; j++) {
               preparedStatement.setObject(j+1,args[j]);
            }
            //4 执行
            // execute()
            //如果是查询操作，有返回值，返回True
            //如果是更新操作，没有返回值，返回false
            //executeUpdate()
            //返回操作影响的行数
            i = preparedStatement.executeUpdate();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtils.closeResource(connection,preparedStatement);
        }
        return 0;
    }
}
